package com.weipai.tbswebviewtest;

import android.os.Bundle;
import android.os.Environment;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;

public class FileActivity extends AppCompatActivity {
    TbsReaderView readerView;
    RelativeLayout linearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);
        linearLayout = findViewById(R.id.rl);


        //打开文件
        //openFile("/storage/emulated/0/智慧民政文件下载/民政部关于发布《民政业务数据共享与交换标准_编码》行业标准的公告20141219.doc");
//        openFile("/storage/emulated/0/智慧民政文件下载/复员退役军人安置信息管理系统-详细设计说明书.docx");
        openFile("/storage/emulated/0/智慧民政文件下载/游戏竞猜.xlsx");
    }

    private void openFile(String path) {
        //通过bundle把文件传给x5,打开的事情交由x5处理
        Bundle bundle = new Bundle();
        //传递文件路径
        bundle.putString("filePath", path);
        File file = new File(Environment.getExternalStorageDirectory() + File.separator +
                "temp");
        if (!file.exists()) {
            file.mkdirs();
        }
        //临时的路径
        bundle.putString("tempPath", Environment.getExternalStorageDirectory() + File.separator +
                "temp");
        readerView = new TbsReaderView(this, new TbsReaderView.ReaderCallback() {
            @Override
            public void onCallBackAction(Integer integer, Object o, Object o1) {

            }
        });
        //加载文件前的初始化工作,加载支持不同格式的插件
        boolean b = readerView.preOpen(getFileType(path), false);
        Log.i("gaogao", "初始化情况" + b);
        if (b) {
            readerView.openFile(bundle);
        }
        // 往容器里添加TbsReaderView控件
        linearLayout.addView(readerView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams
                .MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
    }

    private String getFileType(String paramString) {
        String str = "";

        if (TextUtils.isEmpty(paramString)) {
            Log.d("print", "paramString---->null");
            return str;
        }
        Log.d("print", "paramString:" + paramString);
        int i = paramString.lastIndexOf('.');
        if (i <= -1) {
            Log.d("print", "i <= -1");
            return str;
        }

        str = paramString.substring(i + 1);
        Log.i("gaogao", "文件格式" + str);
        return str;
    }

    @Override
    protected void onDestroy() {
        readerView.onStop();
        super.onDestroy();
    }
}
